/**
 * 
 */

package com.probiz.estore.core.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.view.AbstractTemplateView;

import com.probiz.estore.core.view.MessageContext;

public class VelocityUtil4DB implements InitializingBean {
	protected final transient Log	logger	= LogFactory.getLog(getClass());

	private MessageContext			messageContext;

	private VelocityEngine			velocityEngine;

	/**
	 * 
	 */
	public VelocityUtil4DB() {

	}

	public void afterPropertiesSet() throws Exception {
	}

	public String mergeTemplateIntoString(String templateString,
			Map<String, Object> model) throws VelocityException, IOException {
		/**
		 * Set the same name as
		 * AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE so can
		 * reuse spring.vm macros
		 */
		model.put(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE,
				messageContext);

		StringWriter writer = new StringWriter();
		VelocityContext context = new VelocityContext(model);
		velocityEngine.evaluate(context, writer, "", templateString);
		//去除所有el表达式 匹配${英文数字和点号的组合}
		String strNoEL = writer.toString().replaceAll("\\$\\{[a-zA-Z\\d\\.]*\\}", "");
		strNoEL = strNoEL.replaceAll("\\$[a-zA-Z\\d\\.]*\\(\\)", "");
		return strNoEL;
	}

	public String mergeTemplateIntoString(VelocityEngine velocityEngine,
			String templateString, Map model) throws VelocityException, IOException {
		StringWriter writer = new StringWriter();
		VelocityContext context = new VelocityContext(model);
		velocityEngine.evaluate(context, writer, "", templateString);
		//去除所有el表达式 匹配${英文数字和点号的组合}
		String strNoEL = writer.toString().replaceAll("\\$\\{[a-zA-Z\\d\\.]*\\}", "");
		strNoEL = strNoEL.replaceAll("\\$[a-zA-Z\\d\\.]*\\(\\)", "");
		return strNoEL;
	}

	public void setMessageContext(MessageContext messageContext) {
		this.messageContext = messageContext;
	}

	/**
	 * @param velocityEngine
	 *            the velocityEngine to set
	 */
	public void setVelocityEngine(VelocityEngine in_velocityEngine) {
		velocityEngine = in_velocityEngine;
	}
}
